package edu.wayne.cs.csc4110.hw6.framework;

import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import edu.wayne.cs.csc4110.hw6.framework.Util.UserFileFilter;
import edu.wayne.cs.csc4110.hw6.framework.lobby.GameLobbyServer;
import edu.wayne.cs.csc4110.hw6.framework.plugin.ActivePlugin;
import edu.wayne.cs.csc4110.hw6.framework.state.UserStateImpl;
import edu.wayne.cs.csc4110.hw6.interfaces.Authentication;
import edu.wayne.cs.csc4110.hw6.interfaces.lobby.LobbyServer;
import edu.wayne.cs.csc4110.hw6.interfaces.user.User;

/**
 * Default Authentication for any plugin.
 * 
 * @author Andrew
 * 
 */
public class GameAuthentication implements Authentication {
	public static final String FILE_USER_EXT = ".user";
	public static final String DIRECTORY = "/Temp/users";

	private File dir;
	private FilenameFilter filter;
	private ActivePlugin plugin;

	public GameAuthentication() {
		dir = new File(DIRECTORY);
		filter = new UserFileFilter();
	}

	public GameAuthentication(ActivePlugin plugin) {
		this();
		this.plugin = plugin;

	}

	@Override
	public User login(String username) {
		User user = null;
		if (dir.isDirectory() == false) {
			dir.mkdirs();
		}

		if (isUserFileCreated(username)) {
			try {
				user = new UserStateImpl(username, plugin.getUserExtension()).createState(null);
				user = plugin.createUser(user);
			} catch (ClassNotFoundException e1) {
				e1.printStackTrace();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		} else {
			user = plugin.createUser(username);
			try {
				new UserStateImpl(username, plugin.getUserExtension()).storeState(null, user);
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}

		return user;

	}

	private boolean isUserFileCreated(String username) {
		return Arrays.asList(dir.list(filter)).contains(
				username + FILE_USER_EXT + plugin.getUserExtension() );
	}

	@Override
	public boolean isLoggedIn(String username) {
		LobbyServer server = GameLobbyServer.getInstance();
		for (User u : server.getUsers()) {
			if (u.getUsername().equals(username)) {
				return true;
			}

		}
		return false;
	}

	@Override
	public List<User> getUsers() {

		List<User> users = new ArrayList<User>();
		for (String name : dir.list(filter)) {
			User user = null;
			String username = name.replace(FILE_USER_EXT, "");
			try {
				user = new UserStateImpl(username, plugin.getUserExtension()).createState(null);
				if (user != null)
					users.add(user);
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return users;
	}

}
